computed 和 watch

您所在的位置:网站首页 vue computed和watch computed 和 watch

computed 和 watch

#computed 和 watch| 来源: 网络整理| 查看: 265

computed ——计算属性

computed看上去是方法,但是实际上是计算属性,不需要括号就可以使用,它会根据你所依赖的数据动态显示新的计算结果。计算结果会被缓存,computed的值在getter执行后是会缓存的,只有在它依赖的属性值改变之后,下一次获取computed的值时才会重新调用对应的getter来计算。getter/setter默认是不会做缓存的,Vue做了特殊处理。如果依赖的属性没有变化,就不会重新计算。

import Vue from "vue/dist/vue.js"; Vue.config.productionTip = false; new Vue({ data: { user: { email: "[email protected]", nickname: "来福", phone: "987654321" } }, computed: { displayName: { get() { const user = this.user; return user.nickname || user.email || user.phone; }, set(value) { console.log(value); this.user.nickname = value; } } }, // DRY don't repeat yourself // 不如用 computed 来计算 displayName template: ` {{displayName}} {{displayName}} set `, methods: { add() { console.log("add"); this.displayName = "shanzhu"; } } }).$mount("#app"); watch:侦听属性

一个对象,键是需要观察的表达式,值是对应回调函数。值也可以是方法名,或者包含选项的对象。watcher 更像是一个 data 的数据监听回调,当依赖的 data 的数据变化,执行回调,在方法中会传入 newVal 和 oldVal。Vue 实例将会在实例化时调用 $watch(),遍历 watch 对象的每一个属性。如果你需要在某个数据变化时做一些事情,使用watch。

import Vue from "vue/dist/vue.js"; Vue.config.productionTip = false; new Vue({ data: { n: 0, history: [], inUndoMode: false }, watch: { n: function(newValue, oldValue) { console.log(this.inUndoMode); if (!this.inUndoMode) { this.history.push({ from: oldValue, to: newValue }); } } }, // 不如用 computed 来计算 displayName template: ` {{n}} +1 +2 -1 -2 撤销 {{history}} `, methods: { add1() { this.n += 1; }, add2() { this.n += 2; }, minus1() { this.n -= 1; }, minus2() { this.n -= 2; }, undo() { const last = this.history.pop(); this.inUndoMode = true; console.log("ha" + this.inUndoMode); const old = last.from; this.n = old; // watch n 的函数会异步调用 this.$nextTick(() => { this.inUndoMode = false; }); } } }).$mount("#app");

选项:deep

deep的意思就是深入观察,监听器会一层层的往下遍历,给对象的所有属性都加上这个监听器,但是这样性能开销就会非常大了,任何修改obj里面任何一个属性都会触发这个监听器里的 handler。

为了发现对象内部值的变化,可以在选项参数中指定 deep: true。注意监听数组的变更不需要这么做。

watch: { obj: { handler(newName, oldName) { console.log('obj.a changed'); }, immediate: true, deep: true } }

选项:immediate

在选项参数中指定 immediate: true 将立即以表达式的当前值触发回调:

watch: { firstName: { handler(newName, oldName) { this.fullName = newName + ' ' + this.lastName; }, // 代表在wacth里声明了firstName这个方法之后立即执行handler方法 immediate: true } }

总结

如果一个数据依赖于其他数据,那么把这个数据设计为computed的

如果你需要在某个数据变化时做一些事情,使用watch来观察这个数据变化

优先使用computed



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3